package com.ifonly.security;

import com.ifonly.config.Configuration;
import com.ifonly.handler.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 为了防止通过修改连接访问, 可以采用 Handler 机制实现验证
 * 当然也可以在 config.properties 通过配置 URL 来实现
 *
 * @author ifonly
 * @version 1.0 2016-01-28 17:00
 * @since JDK 1.6
 */
public class PermissionValidationHandler extends Handler {

    private IPermissionValidator validator;
    private String unauthorizedUrl = "/unauthorized";

    public PermissionValidationHandler() {
        this(new DefaultPermissionValidator());
    }

    public PermissionValidationHandler(IPermissionValidator validator) {
        this.validator = validator;
        this.unauthorizedUrl = Configuration.getInstance().getUnauthorizedUrl();
    }

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        if (target.equals(unauthorizedUrl) || validator.validate(target)) {
            next.handle(target, request, response, isHandled);
        } else {
            redirect(unauthorizedUrl, request, response, isHandled);
        }
    }

    public interface IPermissionValidator {
        boolean validate(String target);
    }

    public static class DefaultPermissionValidator implements IPermissionValidator {
        @Override
        public boolean validate(String target) {
            return true;
        }
    }

}
